package com.tanjun.mallservice.web.service.impl;


import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.tanjun.common.constants.DefaultConstant;
import com.tanjun.common.enums.ActStatusEnum;
import com.tanjun.common.exception.BizException;
import com.tanjun.common.utils.ConvertUntil;
import com.tanjun.mallservice.apiservice.enums.plu.PluDescTypeEnum;
import com.tanjun.mallservice.apiservice.enums.plu.PluImgModeEnum;
import com.tanjun.mallservice.apiservice.enums.plu.PluImgTypeEnum;
import com.tanjun.mallservice.web.orm.entity.MallCate;
import com.tanjun.mallservice.web.orm.entity.MallPlu;
import com.tanjun.mallservice.web.orm.entity.MallPluImg;
import com.tanjun.mallservice.web.orm.entity.MallPluSku;
import com.tanjun.mallservice.web.orm.mapper.MallPluMapper;
import com.tanjun.mallservice.web.service.*;
import com.tanjun.mallservice.web.service.request.MallPluRequest;
import com.tanjun.mallservice.web.service.request.PluSkuRequest;
import com.tanjun.mallservice.web.service.request.QueryMallPluRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jjtan
 * @description 针对表【mall_plu(商品信息)】的数据库操作Service实现
 * @createDate 2024-03-21 14:42:16
 */
@Service
public class MallPluServiceImpl extends ServiceImpl<MallPluMapper, MallPlu>
        implements MallPluService {
    @Autowired
    private MallCateService mallCateService;
    @Autowired
    private MallPluSkuService mallPluSkuService;
    @Autowired
    private MallPluImgService mallPluImgService;
    @Autowired
    private MallPluDescService mallPluDescService;

    /**
     * 根据pluId查询商品信息
     *
     * @param pluId
     * @return
     */
    @Override
    @Cacheable(cacheNames = "getPluById", key = "#pluId")
    public MallPlu getPluById(Long pluId) {
        return this.getById(pluId);
    }

    /**
     * 新增或修改商品
     *
     * @param paramVo
     */
    @Override
    @CacheEvict(cacheNames = {"getPluById"}, allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(@Valid MallPluRequest paramVo) {
        if (paramVo.getSkuLevel() >= 1 &&
                (!StringUtils.hasText(paramVo.getSku1Name()) || CollectionUtils.isEmpty(paramVo.getSku1ValueList()))) {
            throw new BizException("规格1不能为空");
        }

        if (paramVo.getSkuLevel() >= 2 &&
                (!StringUtils.hasText(paramVo.getSku2Name()) || CollectionUtils.isEmpty(paramVo.getSku2ValueList()))) {
            throw new BizException("规格2不能为空");
        }
        if (paramVo.getSkuLevel() >= 3 &&
                (!StringUtils.hasText(paramVo.getSku3Name()) || CollectionUtils.isEmpty(paramVo.getSku3ValueList()))) {
            throw new BizException("规格3不能为空");
        }
        MallCate mallCate = mallCateService.getCateById(paramVo.getCateId());
        if (mallCate == null) {
            throw new BizException("分类不存在");
        }
        //判断商品编码是否重复
        MallPlu mallPluCode = this.getOne(QueryChain.of(MallPlu.class)
                .eq(MallPlu::getPluCode, paramVo.getPluCode())
        );
        if (mallPluCode != null && !Objects.equals(mallPluCode.getPluId(), paramVo.getPluId())) {
            throw new BizException("商品编码重复");
        }
        //直接保存
        MallPlu mallPlu = ConvertUntil.convert(paramVo, MallPlu.class);
        mallPlu.setCateFullId(mallCate.getCateLevel() > 1 ?
                mallCate.getCateFullParentId() + DefaultConstant.SPLIT + mallCate.getCateId() : mallCate.getCateId().toString());
        if (paramVo.getSkuLevel() >= 1) {
            mallPlu.setSku1Value(String.join(DefaultConstant.SPLIT, paramVo.getSku1ValueList()));
        }
        if (paramVo.getSkuLevel() >= 2) {
            mallPlu.setSku2Value(String.join(DefaultConstant.SPLIT, paramVo.getSku2ValueList()));
        }
        if (paramVo.getSkuLevel() >= 3) {
            mallPlu.setSku3Value(String.join(DefaultConstant.SPLIT, paramVo.getSku3ValueList()));
        }
        //设置价格
        BigDecimal minPrice = BigDecimal.ZERO;
        BigDecimal tagPrice = BigDecimal.ZERO;
        Integer storeNUm = paramVo.getListSku().stream().mapToInt(d -> d.getSkuStoreNum()).sum();
        PluSkuRequest minPriceSku = paramVo.getListSku()
                .stream()
                .sorted(Comparator.comparing(PluSkuRequest::getSkuPrice))
                .findFirst().orElse(null);
        if (minPriceSku != null) {
            minPrice = minPriceSku.getSkuPrice();
            tagPrice = minPriceSku.getSkuTagPrice();
        }
        mallPlu.setPrice(minPrice);
        mallPlu.setTagPrice(tagPrice);
        mallPlu.setStoreNum(storeNUm);

        //todo 设置商户id、更新人、创建人

        if (paramVo.getPluId() == null) { //新增
            mallPlu.setPluStatus(ActStatusEnum.NEW);
            this.save(mallPlu);
        } else { //修改
            MallPlu old = getPluById(paramVo.getPluId());
            if (old == null) {
                throw new BizException("商品不存在");
            }
            if (old.getPluStatus() == ActStatusEnum.CANCEL) {
                throw new BizException("商品已作废，无法修改");
            }
            this.updateById(mallPlu);
        }

        //规格信息
        List<MallPluSku> listSku = ConvertUntil.convert(paramVo.getListSku(), MallPluSku.class);
        listSku.forEach(d -> {
            d.setPluId(mallPlu.getPluId());
            //todo 设置更新人、创建人
        });
        mallPluSkuService.saveSkuList(listSku);
        //保存图片和说明
        mallPluDescService.saveDescInfo(mallPlu.getPluId(), null, PluDescTypeEnum.PLU, paramVo.getDescInfo());
        List<MallPluImg> listImgs = new ArrayList<>();

        if (!CollectionUtils.isEmpty(paramVo.getPluBannerImgList())) {
            List<MallPluImg> list = paramVo.getPluBannerImgList().stream().map(t -> {
                MallPluImg mallPluImg = new MallPluImg();
                mallPluImg.setImgUrl(t);
                mallPluImg.setPluId(mallPlu.getPluId());
                mallPluImg.setImgMode(PluImgModeEnum.BANNER);
                mallPluImg.setImgType(PluImgTypeEnum.PLU);
                return mallPluImg;
            }).collect(Collectors.toList());

            listImgs.addAll(list);
        }
        for (int i = 0; i < paramVo.getListSku().size(); i++) {
            PluSkuRequest d = paramVo.getListSku().get(i);
            if (!CollectionUtils.isEmpty(d.getSkuBannerImgList())) {
                int finalI = i;
                List<MallPluImg> list = d.getSkuBannerImgList().stream().map(t -> {
                    MallPluImg mallPluImg = new MallPluImg();
                    mallPluImg.setImgUrl(t);
                    mallPluImg.setPluId(mallPlu.getPluId());
                    mallPluImg.setImgMode(PluImgModeEnum.BANNER);
                    mallPluImg.setImgType(PluImgTypeEnum.SKU);
                    mallPluImg.setSkuId(listSku.get(finalI).getSkuId());
                    return mallPluImg;
                }).collect(Collectors.toList());
                listImgs.addAll(list);
            }

            mallPluDescService.saveDescInfo(mallPlu.getPluId(), listSku.get(i).getSkuId(), PluDescTypeEnum.SKU, d.getSkuDescInfo());
        }

        //保存图片
        mallPluImgService.saveImgs(listImgs);

    }

    /**
     * 分页查询数据
     *
     * @param page
     * @param paramVo
     * @return
     */
    @Override
    public Page<MallPlu> queryPagePlu(Page page, QueryMallPluRequest paramVo) {
        Page<MallPlu> re = this.page(page,QueryChain.of(MallPlu.class)
                .eq(MallPlu::getVenId, paramVo.getVenId(),paramVo.getVenId() != null)
                .eq(MallPlu::getCateId, paramVo.getCateId(),paramVo.getCateId() != null)
                .like(MallPlu::getPluName, paramVo.getKeyword(),StringUtils.hasText(paramVo.getKeyword()))
//                .orderBy( PluOrderTypeEnum.DEFAULT.getType()), MallPlu::getSno, MallPlu::getPluId)
//                .orderByDesc(Objects.equals(paramVo.getOrderBy(), PluOrderTypeEnum.SCALE_NUM.getType()), MallPlu::getSalesNum)
//                .orderBy(Objects.equals(paramVo.getOrderBy(), PluOrderTypeEnum.PRICE.getType()), paramVo.getIsAsc(), MallPlu::getPrice)
        );
        return re;
    }

    @Override
    public List<MallPlu> listPluByIds(Collection<Long> listPluIds) {
        return this.listByIds(listPluIds);
    }


}




